<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>async与await结合发送AJAX</title>
</head>
<body>
    <button id="btn">点击获取段子</button>
    <script>
          /**
         * 封装一个函数 sendAJAX 发送 GET AJAX 请求
         * 参数   URL
         * 返回结果 Promise 对象
         */
         function sendAJAX(url){
            
            return new Promise((resolve,reject)=>{

                const xhr=new XMLHttpRequest();
                xhr.responseType="json";
                xhr.open('GET',url);
                xhr.send();
                 //处理结果
                xhr.onreadystatechange=function(){
                    if(xhr.readyState===4){
                        if(xhr.status>=200 && xhr.status<300){
                            //成功的结果
                            resolve(xhr.response);
                        }else{
                            reject(xhr.status)
                        }
                    }
                }
            });
         }

         //http://ajax-base-api-t.itheima.net/api/getbooks

         let btn=document.querySelector('#btn');

         btn.addEventListener('click',async function(){
            let content=await sendAJAX('http://ajax-base-api-t.itheima.net/api/getbooks');
            console.log(content);

            let content2=await sendAJAX('http://ajax-base-api-t.itheima.net/api/getbooks?id=1');
            console.log(content2);

            let content3=await sendAJAX('http://ajax-base-api-t.itheima.net/api/getbooks?id=2');
            console.log(content3);
         });
    </script>
</body>
</html>